#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio
import logging
from logging.handlers import TimedRotatingFileHandler

from aiohttp import web

from com.chenxiaojie.config import config
from com.chenxiaojie.dao import orm
from com.chenxiaojie.filter.logger_filter import logger_factory
from com.chenxiaojie.filter.response_filter import response_factory
from com.chenxiaojie.filter.user_filter import user_auth_factory
from com.chenxiaojie.https.https import create_https_ssl_context
from com.chenxiaojie.mvc.mvc import add_routes, add_static, add_icon
from com.chenxiaojie.template.myjinja import init as init_jinja2

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')

logger = logging.getLogger()
logger.setLevel(logging.INFO)
# sh = logging.StreamHandler()
# sh.setLevel(logging.INFO)
# sh.setFormatter(logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s"))
# logger.addHandler(sh)

fh = TimedRotatingFileHandler(filename="app.log", when="D", interval=1, backupCount=7)
fh.setFormatter(logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s"))
fh.setLevel(logging.INFO)
logger.addHandler(fh)

loop = asyncio.get_event_loop()

# 初始化webapp 与 filter
app = web.Application(middlewares=[
    logger_factory, user_auth_factory, response_factory
])

# 初始化前端模板渲染框架
init_jinja2(app)

# 添加静态资源
add_static(app)

# 添加favicon.ico
add_icon(app)

# 添加路由
add_routes(app, 'com.chenxiaojie.mvc.user_controller')
add_routes(app, 'com.chenxiaojie.mvc.blog_controller')
add_routes(app, 'com.chenxiaojie.mvc.manage_controller')

# 初始化db
loop.run_until_complete(orm.create_pool(loop=loop, **config.configs))
web.run_app(app, host="127.0.0.1", port=443, ssl_context=create_https_ssl_context())

# def index(request):
#     return web.Response(body=b'<h1>chenxiaojie mvc is running!</h1>', headers={'content-type': 'text/html'})

# app.add_routes([web.get('/', index), ])

# web.run_app(app, host="127.0.0.1", port=8443)
